//
//  HomeStatus.swift
//  swift-微博
//
//  Created by chenrin on 2016/12/27.
//  Copyright © 2016年 zhuoheng. All rights reserved.
//

import UIKit

class HomeStatus : NSObject{

    //微博创建时间
    var created_at : String?{
        didSet{
            let createDate = Date.dateWithStr(time: created_at!)
           
            created_at = createDate.descDate
        }
    }
    //微博ID
    var id : Int = 0
    //微博信息内容
    var text : String?
    //微博来源
    var source : String?{
        //"<a href=\"http://app.weibo.com/t/feed/6vtZb0\" rel=\"nofollow\">\U5fae\U535a weibo.com</a>"
        didSet{
            //截取
            if let str = source {
                 //1.1获取开始截取的位置
                let startLocation = (str as NSString).range(of: ">").location + 1
                //1.2截取长度
                let length = (str as NSString).range(of: "<", options: .backwards).location - startLocation
                source = (str as NSString).substring(with: NSRange(location: startLocation, length: length)) 
            }
        }
    }
    //配图数组
    var pic_urls : [[String : Any]]?
    
    //User模型
    var user : HomeUser?    
    
    init(dict : [String:Any]) {
        super.init()
        setValuesForKeys(dict)
    }
    //setValuesForKeys内部会调用下面的方法
    override func setValue(_ value: Any?, forKey key: String) {
        if "user" == key {
            user = HomeUser(dict: value as! [String : Any])
            return
        }
        super.setValue(value, forKey: key)
    }
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
   // var properties = ["created_at","id","text","source","pic_urls"]
    
    //打印模型
//    override var description: String{
//        let dict = dictionaryWithValues(forKeys: properties)
//        return "\(dict)"
//        
//    }
}

// MARK:- 加载微博数据
extension HomeStatus{
    class func loadStatues(finished:@escaping (_ models:[HomeStatus]?,_ error:NSError?)->()){
        
        let pathUrl = "https://api.weibo.com/2/statuses/home_timeline.json"
        let access_token = OAuthModel.getAccount()!.access_token
        let params = ["access_token":access_token]
        
        NetworkTools.requestData(methodType: .GET, urlString: pathUrl, parameters: params, finishedCallback:{(results) in
            
            guard let resultDict = results as? [String:Any] else{
                return
            }
          let models = dict2Model(list: resultDict["statuses"] as! [[String : Any]])
          print(resultDict)
            //通过闭包将数据传出去
            finished(models, nil)
        })
    }
    
    //数组转模型
    class func dict2Model(list:[[String:Any]]) -> [HomeStatus]{
        var modes = [HomeStatus]()
        
        for dict in list{
            
            modes.append(HomeStatus(dict: dict))
        }
        return modes
    }
 }



